<template>
  <c-back-wrap :loading="loading" go-page="市场开发/升级任务管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新增'">
    <QupFormContainer :column="3">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="140px">
        <el-form-item key="marketCode" prop="marketCode" label="市场编码">
          <el-input v-model="formData.marketCode" placeholder="系统自动生成" disabled />
        </el-form-item>
        <el-form-item key="marketName" prop="marketName" label="市场名称">
          <el-input v-model.trim="formData.marketName" placeholder="市场名称" clearable />
        </el-form-item>
        <el-form-item key="marketType" prop="marketType" label="待升级/整改市场类型">
          <c-dict-select v-model="formData.marketType" dict-type-code="TOBE_MARKET_TYPE" clearable placeholder="待升级/整改市场类型" style="width:100%" @change="handleChange" />
        </el-form-item>
        <el-form-item key="marketNatrue" prop="marketNatrue" label="市场属性">
          <!-- 市场属性值范围显示控制：当市场类型选“空白市场”时，
          市场属性仅展示“增商市场A/换商市场B/招商市场C”，
          当市场类型选择“整改市场”时，
          市场属性选择除“增商市场/换商市场/招商市场”以外的其他所有值 -->
          <c-dict-select
            v-model="formData.marketNatrue"
            dict-type-code="MARKET_NATURE"
            clearable
            placeholder="市场属性"
            style="width:100%"
            :include="formData.marketType==='A'?['A','B','C', 'L']:[]"
            :exclude="formData.marketType==='B'?['A','B','C', 'L']:[]"
          />
        </el-form-item>
        <el-form-item key="isExceptionReporting" prop="isExceptionReporting" label="是否属于异常报备">
          <c-dict-select v-model="formData.isExceptionReporting" dict-type-code="BOOLEANS" clearable placeholder="是否属于异常报备" style="width:100%" />
        </el-form-item>
        <el-form-item key="isKeyMarket" prop="isKeyMarket" label="是否重点市场">
          <c-dict-select v-model="formData.isKeyMarket" dict-type-code="BOOLEANS" clearable placeholder="是否重点市场" style="width:100%" />
        </el-form-item>
        <!--空白市场展示 -->
        <template v-if="formData.marketType === 'A'">
          <el-form-item v-if="isEdit" key="isAttractInvestment" prop="isAttractInvestment" label="完成招商">
            <el-switch v-model="formData.isAttractInvestment" active-value="1" inactive-value="0" />
          </el-form-item>
          <el-form-item key="provinceCode" prop="provinceCode" label="省">
            <c-common-search-province
              :id.sync="formData.provinceId"
              v-model="formData.provinceCode"
              :label.sync="formData.provinceName"
              @update:cityLevel="v=>handleCityLevel(v,'province')"
            />
          </el-form-item>
          <el-form-item key="cityCode" prop="cityCode" label="地市">
            <c-common-search-not-province
              :id.sync="formData.cityId"
              v-model="formData.cityCode"
              :label.sync="formData.cityName"
              :disabled="!formData.provinceId"
              :depend-on-observe="formData.provinceId"
              :start-observe="startObserve"
              :parent-id="formData.provinceId"
              @update:cityLevel="v=>handleCityLevel(v,'city')"
            />
          </el-form-item>
          <el-form-item key="districtCode" prop="districtCode" label="区/县">
            <c-common-search-not-province
              :id.sync="formData.districtId"
              v-model="formData.districtCode"
              :label.sync="formData.districtName"
              :disabled="!formData.cityId"
              :depend-on-observe="formData.cityId"
              :start-observe="startObserve"
              :parent-id="formData.cityId"
              @update:cityLevel="v=>handleCityLevel(v,'district')"
            />
          </el-form-item>
          <el-form-item key="streetCode" prop="streetCode" label="街道/乡镇">
            <c-common-search-not-province
              :id.sync="formData.streetId"
              v-model="formData.streetCode"
              :label.sync="formData.streetName"
              :disabled="!formData.districtId"
              :depend-on-observe="formData.districtId"
              :start-observe="startObserve"
              :parent-id="formData.districtId"
              @update:cityLevel="v=>handleCityLevel(v,'street')"
            />
          </el-form-item>
        </template>
        <el-form-item key="agencyCode" prop="agencyCode" label="所属办事处">
          <!-- 筛选范围为启用状态的所有办事处 -->
          <c-common-search-office
            v-model="formData.agencyCode"
            :label.sync="formData.agencyName"
          />
        </el-form-item>
        <el-form-item key="agencyName" prop="agencyName" label="办事处编码">
          <span>{{ formData.agencyCode }}</span>
        </el-form-item>
        <!-- <template v-if="!isNoneMarket"> -->
        <el-form-item key="customerCode" prop="customerCode" label="所属客户">
          <c-common-search-dis
            v-model="formData.customerCode"
            :label.sync="formData.customerName"
            :disabled="!formData.agencyCode"
            :one-category-code_res.sync="oneCategoryCode"
            :depend-on-observe="formData.agencyCode"
            :start-observe="startObserve"
            :before-params="paramsJson => {
              paramsJson.filtersRaw.push({ id: 'agencyCode', property: 'agencyCode', value: formData.agencyCode, operator: '=' })
              $codeOrName(paramsJson.filtersRaw, 'code', 'name')
              return paramsJson
            }"
          />
        </el-form-item>
        <el-form-item key="customerName" prop="customerName" label="客户名称">
          <span>{{ formData.customerName }}</span>
        </el-form-item>
        <el-form-item key="shopCode" prop="shopCode" label="门店">
          <c-common-search-shop
            v-model="formData.shopCode"
            :label.sync="formData.shopName"
            :format-label="v => {
              return `${v.name}(${v.code})`
            }"
            :disabled="!formData.customerCode"
            :depend-on-observe="formData.customerCode"
            :start-observe="startObserve"
            :customer-code="formData.customerCode"
            :city-level_res.sync="formData.cityLevel"
          />
        </el-form-item>
        <el-form-item key="shopName" prop="shopName" label="门店编码">
          <span>{{ formData.shopCode }}</span>
        </el-form-item>
        <template v-if="showOldCustomerCode">
          <el-form-item key="originalCustomerCode" prop="originalCustomerCode" label="原商家客户编码">
            <c-common-search-dis
              v-model="formData.originalCustomerCode"
              :label.sync="formData.originalCustomerName"
              :format-label="v => {
                return v.code
              }"
              :disabled="!formData.agencyCode"
              :depend-on-observe="formData.agencyCode"
              :start-observe="startObserve"
              :filters-raw="[{id:'status',property:'status',value:'[1]', operator: 'IN'}]"
              :before-params="paramsJson => {
                paramsJson.filtersRaw.push({ id: 'agencyCode', property: 'agencyCode', value: formData.agencyCode, operator: '=' })
                $codeOrName(paramsJson.filtersRaw, 'code', 'name')
                return paramsJson
              }"
            />
          </el-form-item>
          <el-form-item key="originalCustomerName" prop="originalCustomerName" label="原商家客户名称">
            <span>{{ formData.originalCustomerName }}</span>
          </el-form-item>
        </template>
        <el-form-item prop="shopBuildNumber" label="门店建设项目号">
          <c-common-search-shop-build
            v-model="formData.shopBuildNumber"
            :label="formData.shopBuildNumber"
            :const-type.sync="formData.shopBuildType"
            :const-schedule.sync="formData.shopBuildStage"
            :disabled="!formData.shopCode"
            :depend-on-observe="formData.shopCode"
            :start-observe="startObserve"
            :before-params="paramsJson=>{
              const filtersRaw = [{id:'shopCode',property:'shopCode',value:formData.shopCode,operator:'='}]
              paramsJson.filtersRaw?paramsJson.filtersRaw.push(...filtersRaw):(paramsJson.filtersRaw=filtersRaw)
              return paramsJson
            }"
          />
        </el-form-item>
        <el-form-item prop="shopBuildType" label="门店建设类型">
          <c-dict-select v-model="formData.shopBuildType" dict-type-code="CONST_TYPE" clearable placeholder="门店建设类型" style="width:100%" />
        </el-form-item>
        <el-form-item prop="shopBuildStage" label="门店整体建设进度">
          <c-dict-range-view v-model="formData.shopBuildStage" dict-type-code="BEFORE_CONST_SCHEDULE" />
        </el-form-item>
        <!-- </template> -->
        <el-form-item key="responsibleCode" prop="responsibleCode" label="客户经理">
          <c-common-search-person-by-office
            v-model="formData.responsibleCode"
            contain-self
            :query-office-code="formData.agencyCode"
            :label.sync="formData.responsibleName"
            :person-tel_res.sync="formData.responsiblePhone"
            :mgr-type-name_res.sync="formData.responsibleType"
            :depend-on-observe="formData.agencyCode"
            :start-observe="startObserve"
          />
        </el-form-item>
        <el-form-item key="responsibleName" prop="responsibleName" label="客户经理编码">
          <span>{{ formData.responsibleCode }}</span>
        </el-form-item>
        <el-form-item key="responsibleType" prop="responsibleType" label="客户经理类型">
          <span>{{ formData.responsibleType }}</span>
        </el-form-item>
        <el-form-item key="responsiblePhone" prop="responsiblePhone" label="客户经理联系电话">
          <span>{{ formData.responsiblePhone }}</span>
        </el-form-item>
        <el-form-item prop="cityLevel" label="城市级别">
          <c-dict-select v-model="formData.cityLevel" :disabled="!isNoneMarket" dict-type-code="CITY_LEVEL" clearable placeholder="城市级别" style="width:100%" />
          <!-- <c-dict-range-view :value="formData.cityLevel" dict-type-code="CITY_LEVEL" /> -->
        </el-form-item>
        <el-form-item key="dataSource" prop="dataSource" label="数据来源">
          <c-dict-select v-model="formData.dataSource" dict-type-code="CTM_MARKET_DATA_FROM" :exclude="isEdit?[]:['D']" clearable placeholder="数据来源" style="width:100%" />
        </el-form-item>
        <el-form-item key="dataSourceMsg" prop="dataSourceMsg" label="数据来源描述" :span="24">
          <el-input v-model="formData.dataSourceMsg" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="数据来源描述" clearable />
        </el-form-item>
        <el-form-item key="registerTime" prop="registerTime" label="登记日期">
          <el-date-picker v-model="formData.registerTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="登记日期" />
        </el-form-item>
        <el-form-item key="taskType" prop="taskType" label="任务类型">
          <c-dict-select v-model="formData.taskType" dict-type-code="CTM_MARKET_TASK_TYPE" clearable placeholder="任务类型" style="width:100%" />
        </el-form-item>
        <el-form-item key="upgradeRequirement" prop="upgradeRequirement" label="升级改造要求" :span="24">
          <el-input v-model="formData.upgradeRequirement" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="升级改造要求" clearable />
        </el-form-item>
        <el-form-item key="earliestDistributionMonth" prop="earliestDistributionMonth" label="最早分配月份">
          <span>{{ formData.earliestDistributionMonth }}</span>
        </el-form-item>
        <el-form-item key="allocationNumber" prop="allocationNumber" label="分配次数">
          <span>{{ formData.allocationNumber || 0 }}</span>
        </el-form-item>
        <el-form-item key="allocationStatus" prop="allocationStatus" label="当前分配状态">
          <c-dict-range-view :value="formData.allocationStatus" dict-type-code="CTM_ALLOCATE_STYLE" />
        </el-form-item>
        <el-form-item key="marketFollowUpStage" prop="marketFollowUpStage" label="市场跟进进度">
          <c-dict-select v-model="formData.marketFollowUpStage" :disabled="partDisabled" dict-type-code="CTM_MARKET_BUID_PROGRESS" :exclude="['D']" clearable placeholder="市场跟进进度" style="width:100%" />
        </el-form-item>
        <el-form-item key="settlementDate" prop="settlementDate" label="结案日期">
          <el-date-picker v-model="formData.settlementDate" :disabled="addDisabled || partDisabled" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结案日期" @change="handleSettlementDateChange" />
        </el-form-item>
        <el-form-item key="settlementMethod" prop="settlementMethod" label="结案方式">
          <c-dict-select v-model="formData.settlementMethod" :disabled="addDisabled || partDisabled" dict-type-code="CTM_CLOSED_TYPE" clearable placeholder="结案方式" style="width:100%" />
        </el-form-item>
        <el-form-item key="remark" prop="remark" label="说明" :span="24">
          <el-input v-model="formData.remark" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="说明" clearable />
        </el-form-item>
        <el-form-item key="cutOffTime" prop="cutOffTime" label="限期到期日">
          <el-date-picker v-model="formData.cutOffTime" type="date" value-format="yyyy-MM-dd" placeholder="限期到期日" />
        </el-form-item>
        <el-form-item key="appraisalPlan" prop="appraisalPlan" label="考核计划">
          <c-dict-select v-model="formData.appraisalPlan" dict-type-code="CTM_APPRAISAL_PLAN" clearable placeholder="考核计划" style="width:100%" />
        </el-form-item>
      </el-form>
    </QupFormContainer>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确定</c-button>
    </div>
  </c-back-wrap>
</template>

<script>
import { detailTask, addTask, editTask } from '@/api/channelTask2/storeUpgradeTask'
export default {
  name: 'AddEdit',
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      oneCategoryCode: '', // 客户一级分类
      startObserve: false,
      formData: {
        marketCode: '',
        marketName: '',
        marketType: '',
        isKeyMarket: '',
        isExceptionReporting: '',
        isAttractInvestment: '',
        provinceCode: '',
        provinceId: '',
        provinceName: '',
        cityCode: '',
        cityId: '',
        cityName: '',
        districtCode: '',
        districtId: '',
        districtName: '',
        streetCode: '',
        streetId: '',
        streetName: '',
        cityLevel: '',
        agencyCode: '',
        agencyName: '',
        customerCode: '',
        customerName: '',
        originalCustomerCode: '', // 原商家
        originalCustomerName: '', // 原商家
        shopCode: '',
        shopName: '',
        shopBuildNumber: '',
        shopBuildType: '',
        shopBuildStage: '',
        dataSource: '',
        dataSourceMsg: '',
        registerTime: '',
        taskType: '', // 任务类型
        marketNatrue: '',
        upgradeRequirement: '',
        earliestDistributionMonth: '',
        allocationNumber: '',
        allocationStatus: '',
        marketFollowUpStage: '',
        settlementDate: '',
        settlementMethod: '',
        remark: '',
        cutOffTime: '',
        appraisalPlan: '',
        responsibleCode: '',
        responsibleName: '',
        responsiblePhone: '',
        responsibleType: ''
      },
      detail: {},
      loading: false
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    isNoneMarket() {
      return this.formData.marketType === 'A'
    },
    isEnd() {
      return this.formData.marketFollowUpStage === 'C'
    },
    formRules() {
      const isQyqjkh = this.oneCategoryCode === 'Z230'
      const isUnderway = this.formData.marketFollowUpStage === 'B' && !isQyqjkh

      const { marketType, marketNatrue, settlementDate } = this.formData
      // 1.当市场类型为开发市场，市场属性为换商市场时，原客户编码设置为必填项，且需过滤已经停用的数据；
      const originalCustomerCodeRequired = marketType === 'A' && marketNatrue === 'B'
      // 2.当市场类型为开发市场，市场属性为增开分店市，客户编码设置为必填；
      const customerCodeRequired = marketType === 'A' && marketNatrue === 'L'
      // 【待开发及整改市场总表/月任务】当“结案日期”有值时，需控制“结案方式”必填
      const settlementMethodRequired = !!settlementDate
      return {
        marketType: [{ required: true, message: '请选择待升级/整改市场类型', trigger: 'change' }],
        isKeyMarket: [{ required: true, message: '请选择是否重点市场', trigger: 'change' }],
        marketName: [{ required: true, message: '请输入市场名称', trigger: 'change' }],
        isAttractInvestment: [{ required: true, message: '请选择是否完成招商', trigger: 'change' }],
        agencyCode: [{ required: true, message: '请选择所属办事处', trigger: 'change' }],
        dataSource: [{ required: true, message: '请选择数据来源', trigger: 'change' }],
        registerTime: [{ required: true, message: '请选择登记日期', trigger: 'change' }],
        // taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
        marketNatrue: [{ required: true, message: '请选择市场属性', trigger: 'change' }],
        provinceCode: [{ required: true, message: '请选择省', trigger: 'change' }],
        cityCode: [{ required: true, message: '请选择地市', trigger: 'change' }],
        districtCode: [{ required: !this.isNoneMarket, message: '请选择区/县', trigger: 'change' }],
        // streetCode: [{ required: true, message: '请选择街道/乡镇', trigger: 'change' }],
        marketFollowUpStage: [{ required: true, message: '请选择市场跟进进度', trigger: 'change' }],
        customerCode: [{ required: !this.isNoneMarket || customerCodeRequired, message: '请选择客户', trigger: 'change' }],
        shopCode: [{ required: !this.isNoneMarket, message: '请选择门店', trigger: 'change' }],
        shopBuildNumber: [{ required: this.formData.marketFollowUpStage === 'C', message: '请选择门店建设项目号', trigger: 'change' }],
        settlementDate: [{ required: this.isEnd && this.isEdit, message: '请选择结案日期', trigger: 'change' }],
        settlementMethod: [{ required: settlementMethodRequired, message: '请选择结案方式', trigger: 'change' }],
        appraisalPlan: [{ required: true, message: '请选择考核计划', trigger: 'change' }],
        responsibleCode: [{ required: true, message: '请选择客户经理', trigger: 'change' }],
        originalCustomerCode: [{ required: originalCustomerCodeRequired, message: '请选择原商家客户编码', trigger: 'change' }]
      }
    },
    // 40742   【待开发及整改市场管理】编辑功能控制调整
    // 2.编辑字段控制：当分配状态值为“已分配”时，
    // “市场跟进进度/结案方式/结案日期”不允许编辑，其他字段编辑方式不变
    partDisabled() {
      return this.isEdit && this.detail.allocationStatus === 'B'
    },
    // 71386   【待开发及整改市场管理】页面新增/新增导入时，“结案日期、结案方式”不允许写入
    addDisabled() {
      return !this.isEdit
    },
    // 显示原商家
    showOldCustomerCode() {
      const { marketType, marketNatrue } = this.formData
      return marketType === 'A' && marketNatrue === 'B'
    }
  },
  watch: {
    showOldCustomerCode: {
      handler(v) {
        if (!v) {
          this.$set(this.formData, 'originalCustomerCode', '')
          this.$set(this.formData, 'originalCustomerName', '')
        }
      }
    }
  },
  created() {
    if (this.isEdit) {
      this.syncFormData()
    } else {
      this.startObserve = true
      this.$set(this.formData, 'marketFollowUpStage', 'A')
    }
  },
  methods: {
    getDetailData() {
      this.loading = true
      return detailTask(this.id).then(res => {
        this.loading = false
        this.detail = res.data
      }).catch(() => {
        this.loading = false
      })
    },
    syncFormData() {
      this.getDetailData().then(() => {
        this.formData = { ...this.detail }
        setTimeout(() => {
          this.startObserve = true
        }, 500)
      })
    },
    handleCityLevel(cityLevel, type) {
      switch (type) {
        case 'province':
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'city':
          if (cityLevel === '' && this.formData.provinceCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'district':
          if (cityLevel === '' && this.formData.cityCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'street':
          if (cityLevel === '' && this.formData.districtCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break

        default:
          break
      }
    },
    handleCustomerName(v) {
      // if (!this.isNoneMarket) {
      //   this.$set(this.formData, 'marketName', v)
      // }
    },
    handleSettlementDateChange(v) {
      if (v && this.formData.marketFollowUpStage !== 'C') {
        this._marketFollowUpStage = this.formData.marketFollowUpStage
        this.$set(this.formData, 'marketFollowUpStage', 'C')
      } else if (this._marketFollowUpStage) {
        this.$set(this.formData, 'marketFollowUpStage', this._marketFollowUpStage)
      }
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleConfirm() {
      return this.$refs.form.validate().then(() => {
        const data = { ...this.formData }
        return (this.isEdit ? editTask : addTask)(data).then(() => {
          this.$message.success('操作成功!')
          this.$pageStack.pop(this.isEdit ? 'onPage' : 'opCondition')
        })
      })
    },
    handleChange(v) {
      this.$set(this.formData, 'cityLevel', '')
      if (v === 'A') {
        this.$set(this.formData, 'customerCode', '')
        this.$set(this.formData, 'customerName', '')
        this.$set(this.formData, 'shopCode', '')
        this.$set(this.formData, 'shopName', '')
      } else {
        this.$set(this.formData, 'provinceId', '')
        this.$set(this.formData, 'provinceCode', '')
        this.$set(this.formData, 'provinceName', '')
        this.$set(this.formData, 'cityId', '')
        this.$set(this.formData, 'cityCode', '')
        this.$set(this.formData, 'cityName', '')
        this.$set(this.formData, 'districtId', '')
        this.$set(this.formData, 'districtCode', '')
        this.$set(this.formData, 'districtName', '')
        this.$set(this.formData, 'streetId', '')
        this.$set(this.formData, 'streetCode', '')
        this.$set(this.formData, 'streetName', '')
      }
    }
  }
}
</script>
